package com.globo.devsup.server.rpc;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import com.globo.devsup.client.rpc.LoginRPC;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class LoginRPCImpl extends RemoteServiceServlet implements LoginRPC {

	private static final String EOT 			= "EOT";
    private static final int 	SERVER_PORT 	= 40000;
    private static final int 	SERVER_TIMEOUT 	= 600000;	
    private static final String SERVER_HOST 	= "cvs.globoi.com";  

    private static final int 	SERVER_TRANSFER_PORT 	= 41000;
    private static final String SERVER_TRANSFER_HOST 	= "riosd02.globoi.com";  //  @jve:decl-index=0:
    
    public static boolean 	logOn 			= false;
	public static boolean validacaoSSH		= false;
	public String username = null; 
	public String password = null;
	public String group    = null;  
	public boolean login   = false;
	public boolean inGroup = false;


	public String getUsername() {
		return username;
	   }


	public void setUsername(String username) {
		this.username = username;
	}
	

	public String getPassword() {
		return password;
	}
	

	public void setPassword(String password) {
		this.password = password;
	}

	public String getGroup() {
		return group;
	}
	

	public void setGroup(String group) {
		this.group = group;
	}
	

	public boolean isLogin() {
		return login;
	}
	
	public String validate(String userName, String pass, String globo) {
		if (Boolean.getBoolean(globo)) 
			return validaLoginSSH(userName, pass);
		else 
			return validaLoginLDAP(userName, pass);
	}
	
	public String validaLoginSSH(String userName, String pass) {
		
		String result = callValidaUsuarioSSH(userName, pass,"sysadm");

		if (isLogin()) {
			setUsername(userName);
			setPassword(pass);
			if (inGroup)  {
				setGroup("sysadm");
			}
			else {
				result = callValidaUsuarioSSH(userName, pass,"globocom");
				if (inGroup)  {
					setGroup("globocom");
				} else {
					setGroup("");
				}
			}
		} else {
			result = "Usuário inválido";
		}
		return result;
	}
	
	public String validaLoginLDAP(String userName, String pass) {

		String result =  callValidaUsuarioLDAP(userName, pass);

		if (isLogin()) {
			setUsername(userName);
			setPassword(pass);
			setGroup("validacaoLDAP");
	
		} else {
			//apresentaMensagem("Usuário inválido");
		}
		
		return result;
	}
	
	
	public String callValidaUsuarioLDAP (String usuario, String password) {
		String result = "";
	   String address 	= SERVER_HOST;
	   int porta 		= SERVER_PORT;
	   ObjectInputStream entrada = null;
	   ObjectOutputStream saida = null;
	   Socket cliente = null;
	   result += "Conectando ao servidor ...<br>";
	   String ret = null;
	   String cmd = "1;"+usuario+";"+password;
	   
		try {
			cliente = new Socket(address,porta);
			cliente.setSoTimeout(SERVER_TIMEOUT);
			result += "Conexao aceita de: "+cliente.getInetAddress().toString() + "<br>";
			result += "Obtendo canal de saida<br>";
		saida = new ObjectOutputStream(cliente.getOutputStream());
		saida.flush();
		
		result += "SENT: "+cmd+"<br>";
		saida.writeObject(cmd);
		String msg = "";
		result += "Obtendo canal de entrada<br>";
		entrada = new ObjectInputStream(cliente.getInputStream());
		do {
			msg = (String) entrada.readObject();
			result += "RCV: "+msg+"<br>";
			if (msg.contains("retornoOK")) ret = msg.toString();
		}while(!msg.equals(EOT));
		setLogin(true);
	
	} catch (Exception e) {
		result += "Erro: "+e+"<br>";
		//setMessage(e.getMessage());
	} finally{
		
			try {
				if (entrada != null) entrada.close();
				if (saida!=null) saida.close();
				if (cliente != null) {
					result += "Encerrando a conexao<br>";
					cliente.close();
					cliente = null;
					result += "Conexao encerrada<br>";
					if (ret != null) {
						String[] auxret = ret.split(",");
						if (auxret[1].compareTo("true")==0) login   = true; else login = false;
						if (auxret[2].compareTo("true")==0) inGroup = true; else inGroup = false;
					}
					return ret;
				}
			} catch (IOException e1) {
				result += "Erro ao encerrar a conexao - "+e1;
					//setMessage(e1.getMessage());
				}
				return ret;
		}
   }
   
   
   public void setLogin(boolean login) {
	this.login = login;
	}


	public String callValidaUsuarioSSH (String usuario, String password, String grupo) {
		String result = "";
		   String address 	= SERVER_HOST;
		   int porta 		= SERVER_PORT;
		   ObjectInputStream entrada = null;
		   ObjectOutputStream saida = null;
		   Socket cliente = null;
	       result += "Conectando ao servidor ...<br>";
	       String ret = null;
	       String cmd = "0;"+usuario+";"+password+";"+grupo;
	       
			try {
				cliente = new Socket(address,porta);
				cliente.setSoTimeout(SERVER_TIMEOUT);
	            result += "Conexao aceita de: "+cliente.getInetAddress().toString()+"<br>";
	            result += "Obtendo canal de saida<br>";
				saida = new ObjectOutputStream(cliente.getOutputStream());
				saida.flush();
				
				result += "SENT: "+cmd+"<br>";
				saida.writeObject(cmd);
				String msg = "";
				result += "Obtendo canal de entrada<br>";
				entrada = new ObjectInputStream(cliente.getInputStream());
				do {
					msg = (String) entrada.readObject();
					result += "RCV: "+msg+"<br>";	
					if (msg.contains("retornoOK")) ret = msg.toString();
				}while(!msg.equals(EOT));
				setLogin(true);
			} catch (Exception e) {
				result += "Erro: "+e+"<br>";
				System.exit(1);
			} finally{
				
					try {
						if (entrada != null) entrada.close();
						if (saida!=null) saida.close();
						if (cliente != null) {
							result += "Encerrando a conexao<br>";
							cliente.close();
							cliente = null;
							result += "Conexao encerrada<br>";
							if (ret != null) {
								String[] auxret = ret.split(",");
								if (auxret[1].compareTo("true")==0) login   = true; else login = false;
								if (auxret[2].compareTo("true")==0) inGroup = true; else inGroup = false;
							}
							return ret;
						}
					} catch (IOException e1) {
						result = "Erro ao encerrar a conexao - "+e1;
					}
					return ret;
			}
				
		} 
}
